//
//  CHDefBordCheckButton.swift
//  nurseApp
//
//  Created by CY on 2025/9/9.
//

import UIKit

/// 选择边框按钮 - 单选按钮组组件
public class CHDefBordCheckButton: UIView {
    
    // MARK: - 公有属性
    
    /// 当前选中的按钮索引
    public private(set) var selectedIndex: Int = 0
    
    /// 当前选中的标题
    public var selectedTitle: String? {
        guard selectedIndex < titleArr.count else { return nil }
        return titleArr[selectedIndex]
    }
    
    /// 按钮点击回调
    public var btnClickBlock: ((String, Int) -> Void)?
    
    
    // MARK: - 私有属性
    
    private var titleArr: [String] = []
    private var buttonArr: [UIButton] = []
    private var lineArr: [UIView] = []
    
    // 样式配置
    private var defaultColor: UIColor = .black
    private var selectedColor: UIColor = .blue
    private var defaultBackgroundColor: UIColor = .clear
    private var selectedBackgroundColor: UIColor = .white
    private var lineColor: UIColor = .blue
    private var lineWidth: CGFloat = 0 // 0表示自适应
    private var lineHeight: CGFloat = 2.0
    private var fontSize: CGFloat = 14.0
    private var cornerRadius: CGFloat = 0
    private var borderWidth: CGFloat = 1.0 // 默认边框宽度为1
    private var defaultBorderColor: UIColor = .lightGray
    private var selectedBorderColor: UIColor = .blue
    
    private var currentBtn: UIButton?
    private var stackView: UIStackView!
    
    
    // MARK: - 初始化方法
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    public convenience init(titles: [String]) {
        self.init(frame: .zero)
        self.titleArr = titles
        createButtons()
    }
    
    private func commonInit() {
        setupStackView()
    }
    
    private func setupStackView() {
        stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 0
        stackView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(stackView)
        
        NSLayoutConstraint.activate([
            stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
            stackView.topAnchor.constraint(equalTo: topAnchor),
            stackView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
    
    
    // MARK: - 公有方法
    
    /// 设置标题数组和样式配置
    public func configure(titles: [String],
                   defaultColor: UIColor = .black,
                   selectedColor: UIColor = .blue,
                   defaultBackgroundColor: UIColor = .clear,
                   selectedBackgroundColor: UIColor = .white,
                   lineColor: UIColor = .blue,
                   lineWidth: CGFloat = 0,
                   lineHeight: CGFloat = 2.0,
                   fontSize: CGFloat = 14.0,
                   cornerRadius: CGFloat = 0,
                   borderWidth: CGFloat = 1.0,
                   defaultBorderColor: UIColor = .lightGray,
                   selectedBorderColor: UIColor = .blue) {
        self.titleArr = titles
        self.defaultColor = defaultColor
        self.selectedColor = selectedColor
        self.defaultBackgroundColor = defaultBackgroundColor
        self.selectedBackgroundColor = selectedBackgroundColor
        self.lineColor = lineColor
        self.lineWidth = lineWidth
        self.lineHeight = lineHeight
        self.fontSize = fontSize
        self.cornerRadius = cornerRadius
        self.borderWidth = borderWidth
        self.defaultBorderColor = defaultBorderColor
        self.selectedBorderColor = selectedBorderColor
        
        createButtons()
    }
    
  
    /**
     点击了
     */
    public func btnClickBlockFun(clouse:@escaping (_ title:String, _ index:Int) -> Void){
        self.btnClickBlock = clouse
    }
    
    /// 设置选中索引
    public func setSelectedIndex(_ index: Int, animated: Bool = true) {
        guard index >= 0, index < buttonArr.count else { return }
        let button = buttonArr[index]
        buttonTapped(button, animated: animated)
    }
    
    /// 隐藏线条指示器
    public func hideLineView(_ hidden: Bool) {
        lineArr.forEach { $0.isHidden = hidden }
    }
    
    /// 更新字体大小
    public func updateFontSize(_ fontSize: CGFloat) {
        self.fontSize = fontSize
        buttonArr.forEach { $0.titleLabel?.font = UIFont.systemFont(ofSize: fontSize) }
        updateLinePositions()
    }
    
    
    // MARK: - 私有方法
    
    private func createButtons() {
        // 清除旧视图
        buttonArr.forEach {
            stackView.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        buttonArr.removeAll()
        
        lineArr.forEach { $0.removeFromSuperview() }
        lineArr.removeAll()
        
        // 创建新按钮
        for (index, title) in titleArr.enumerated() {
            let button = UIButton(type: .custom)
            button.setTitle(title, for: .normal)
            button.setTitleColor(defaultColor, for: .normal)
            button.setTitleColor(selectedColor, for: .selected)
            button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
            button.tag = index
            
            // 添加圆角
            if cornerRadius > 0 {
                button.layer.cornerRadius = cornerRadius
                button.layer.masksToBounds = true
            }
            
            // 添加边框
            button.layer.borderWidth = borderWidth
            
            // 添加点击事件
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
            
            stackView.addArrangedSubview(button)
            buttonArr.append(button)
            
            // 创建线条指示器
            let lineView = UIView()
            lineView.backgroundColor = lineColor
            lineView.isHidden = (index != 0)
            addSubview(lineView)
            lineArr.append(lineView)
            
            // 默认选中第一个
            if index == 0 {
                button.isSelected = true
                button.backgroundColor = selectedBackgroundColor
                button.layer.borderColor = selectedBorderColor.cgColor
                currentBtn = button
            } else {
                button.backgroundColor = defaultBackgroundColor
                button.layer.borderColor = defaultBorderColor.cgColor
            }
        }
        
        updateLinePositions()
    }
    
    private func updateLinePositions() {
        for (index, lineView) in lineArr.enumerated() {
            guard index < buttonArr.count else { continue }
            
            let button = buttonArr[index]
            
            // 计算线条宽度
            let calculatedWidth: CGFloat
            if lineWidth > 0 {
                calculatedWidth = lineWidth
            } else {
                // 自适应宽度
                calculatedWidth = widthForString(button.currentTitle ?? "", font: button.titleLabel?.font ?? UIFont.systemFont(ofSize: fontSize))
            }
            
            // 计算线条位置
            let lineX = button.frame.midX - calculatedWidth / 2
            let lineY = button.frame.maxY - lineHeight
            
            lineView.frame = CGRect(x: lineX, y: lineY, width: calculatedWidth, height: lineHeight)
        }
    }
    
    private func widthForString(_ string: String, font: UIFont) -> CGFloat {
        let attributes = [NSAttributedString.Key.font: font]
        let size = (string as NSString).size(withAttributes: attributes)
        return ceil(size.width)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        updateLinePositions()
    }
    
    
    // MARK: - 按钮点击事件
    
    @objc private func buttonTapped(_ sender: UIButton) {
        buttonTapped(sender, animated: true)
    }
    
    private func buttonTapped(_ sender: UIButton, animated: Bool) {
        guard sender != currentBtn else { return }
        
        // 更新选中状态
        currentBtn?.isSelected = false
        currentBtn?.backgroundColor = defaultBackgroundColor
        currentBtn?.layer.borderColor = defaultBorderColor.cgColor
        
        sender.isSelected = true
        sender.backgroundColor = selectedBackgroundColor
        sender.layer.borderColor = selectedBorderColor.cgColor
        currentBtn = sender
        
        selectedIndex = sender.tag
        
        // 更新线条指示器
        updateLineIndicator(animated: animated)
        
        // 执行回调
        btnClickBlock?(sender.currentTitle ?? "", selectedIndex)
    }
    
    private func updateLineIndicator(animated: Bool) {
        let updateBlock = {
            for (index, lineView) in self.lineArr.enumerated() {
                lineView.isHidden = (index != self.selectedIndex)
                
                if !lineView.isHidden {
                    let button = self.buttonArr[index]
                    let lineX = button.frame.midX - lineView.frame.width / 2
                    let lineY = button.frame.maxY - self.lineHeight
                    lineView.frame = CGRect(x: lineX, y: lineY, width: lineView.frame.width, height: self.lineHeight)
                }
            }
        }
        
        animated ? UIView.animate(withDuration: 0.3, animations: updateBlock) : updateBlock()
    }
}
